// DOM Elements
const createTemplateBtn = document.getElementById('createTemplateBtn');
const manageTemplatesBtn = document.getElementById('manageTemplatesBtn');
const enterDataBtn = document.getElementById('enterDataBtn');
const viewDataBtn = document.getElementById('viewDataBtn');
const batchDownloadBtn = document.getElementById('batchDownloadBtn');

const templateCreation = document.getElementById('templateCreation');
const templateManagement = document.getElementById('templateManagement');
const dataEntry = document.getElementById('dataEntry');
const dataView = document.getElementById('dataView');
const batchDownload = document.getElementById('batchDownload');

const templateForm = document.getElementById('templateForm');
const fieldsContainer = document.getElementById('fieldsContainer');
const addFieldBtn = document.getElementById('addFieldBtn');
const templateSelect = document.getElementById('templateSelect');
const viewTemplateSelect = document.getElementById('viewTemplateSelect');
const downloadTemplateSelect = document.getElementById('downloadTemplateSelect');
const dataEntryForm = document.getElementById('dataEntryForm');
const dataViewContainer = document.getElementById('dataViewContainer');
const saveDataBtn = document.getElementById('saveDataBtn');
const downloadBtn = document.getElementById('downloadBtn');

// 分页相关
const prevPageBtn = document.getElementById('prevPageBtn');
const nextPageBtn = document.getElementById('nextPageBtn');
const pageInfo = document.getElementById('pageInfo');
let currentPage = 1;
const itemsPerPage = 10;

// Field types for template creation
const fieldTypes = [
    { value: 'text', label: '文本' },
    { value: 'number', label: '数字' },
    { value: 'date', label: '日期' },
    { value: 'email', label: '邮箱' },
    { value: 'textarea', label: '多行文本' },
    { value: 'select', label: '下拉框' },
    { value: 'image', label: '图片' }
];

// 添加示例选项
const exampleOptions = {
    select: [
        { value: 'option1', label: '选项1' },
        { value: 'option2', label: '选项2' },
        { value: 'option3', label: '选项3' }
    ]
};

// 添加仪表盘按钮
const dashboardBtn = document.getElementById('dashboardBtn');
const dashboard = document.getElementById('dashboard');

// 为仪表盘按钮添加data-section属性
dashboardBtn.dataset.section = 'dashboard';

// 添加仪表盘按钮点击事件
dashboardBtn.addEventListener('click', async () => {
    showSection(dashboard);
    try {
        await db.ensureConnection();
        await updateDashboard();
    } catch (error) {
        console.error('初始化仪表盘时出错：', error);
        alert('初始化仪表盘时出错：' + error.message);
    }
});

// 初始化时显示仪表盘
(async () => {
    try {
        await db.ensureConnection();
        showSection(dashboard);
        await updateDashboard();
    } catch (error) {
        console.error('初始化仪表盘时出错：', error);
        alert('初始化仪表盘时出错：' + error.message);
    }
})();

// Navigation
function showSection(section) {
    // 隐藏所有section
    [templateCreation, templateManagement, dataEntry, dataView, batchDownload, dashboard].forEach(s => {
        s.classList.add('hidden');
    });
    
    // 显示选中的section
    section.classList.remove('hidden');

    // 更新菜单项的激活状态
    const buttons = document.querySelectorAll('.sidebar button');
    buttons.forEach(button => {
        button.classList.remove('active');
    });
    
    // 根据当前显示的section激活对应的菜单项
    const activeButton = document.querySelector(`.sidebar button[data-section="${section.id}"]`);
    if (activeButton) {
        activeButton.classList.add('active');
    }

    // 如果是仪表盘，更新数据
    if (section.id === 'dashboard') {
        updateDashboard().catch(error => {
            console.error('更新仪表盘时出错：', error);
            alert('更新仪表盘时出错：' + error.message);
        });
    }
}

// 为菜单按钮添加data-section属性
createTemplateBtn.dataset.section = 'templateCreation';
manageTemplatesBtn.dataset.section = 'templateManagement';
enterDataBtn.dataset.section = 'dataEntry';
viewDataBtn.dataset.section = 'dataView';
batchDownloadBtn.dataset.section = 'batchDownload';

createTemplateBtn.addEventListener('click', () => {
    showSection(templateCreation);
    templateForm.reset();
    fieldsContainer.innerHTML = '';
});

manageTemplatesBtn.addEventListener('click', () => {
    showSection(templateManagement);
    loadTemplates();
});

enterDataBtn.addEventListener('click', () => {
    showSection(dataEntry);
    loadTemplateSelect();
});

viewDataBtn.addEventListener('click', () => {
    showSection(dataView);
    loadViewTemplateSelect();
});

batchDownloadBtn.addEventListener('click', () => {
    showSection(batchDownload);
    loadDownloadTemplateSelect();
});

// Template Creation
addFieldBtn.addEventListener('click', () => {
    const fieldDiv = document.createElement('div');
    fieldDiv.className = 'field-item';
    
    const fieldName = document.createElement('input');
    fieldName.type = 'text';
    fieldName.placeholder = '字段名称';
    fieldName.required = true;

    const fieldType = document.createElement('select');
    fieldType.required = true;
    fieldTypes.forEach(type => {
        const option = document.createElement('option');
        option.value = type.value;
        option.textContent = type.label;
        fieldType.appendChild(option);
    });

    const optionsContainer = document.createElement('div');
    optionsContainer.className = 'options-container hidden';
    optionsContainer.innerHTML = `
        <div class="options-input-container">
            <textarea class="options-textarea" placeholder="请输入选项，格式：选项1:值1&#10;选项2:值2"></textarea>
            <button type="button" class="add-option-btn">添加选项</button>
        </div>
        <div class="options-list"></div>
        <div class="options-format">
            <small>格式说明：每行一个选项，格式为"选项:值"，例如：</small>
            <pre>选项1:值1
选项2:值2
选项3:值3</pre>
        </div>
    `;

    const removeBtn = document.createElement('button');
    removeBtn.textContent = '删除';
    removeBtn.type = 'button';
    removeBtn.onclick = () => fieldDiv.remove();

    fieldDiv.appendChild(fieldName);
    fieldDiv.appendChild(fieldType);
    fieldDiv.appendChild(optionsContainer);
    fieldDiv.appendChild(removeBtn);
    fieldsContainer.appendChild(fieldDiv);

    // 监听字段类型变化
    fieldType.addEventListener('change', () => {
        optionsContainer.classList.toggle('hidden', fieldType.value !== 'select');
    });

    // 更新添加选项按钮的事件处理
    const addOptionBtn = optionsContainer.querySelector('.add-option-btn');
    addOptionBtn.addEventListener('click', () => {
        const textarea = optionsContainer.querySelector('.options-textarea');
        const optionsList = optionsContainer.querySelector('.options-list');
        const options = textarea.value.split('\n')
            .map(line => line.trim())
            .filter(line => line)
            .map(line => {
                const [label, value] = line.split(':').map(s => s.trim());
                return { label, value: value || label };
            });
        
        if (options.length > 0) {
            optionsList.innerHTML = '';
            options.forEach(option => {
                const optionDiv = document.createElement('div');
                optionDiv.className = 'option-item';
                optionDiv.innerHTML = `
                    <span>${option.label}:${option.value}</span>
                    <button type="button" class="remove-option-btn">×</button>
                `;
                
                optionDiv.querySelector('.remove-option-btn').onclick = () => {
                    optionDiv.remove();
                    updateOptionsData(fieldDiv);
                };
                
                optionsList.appendChild(optionDiv);
            });
            textarea.value = '';
            updateOptionsData(fieldDiv);
        }
    });

    // 添加更新选项数据的函数
    function updateOptionsData(fieldDiv) {
        const optionsList = fieldDiv.querySelector('.options-list');
        const options = Array.from(optionsList.children).map(option => {
            const [label, value] = option.textContent.split(':');
            return { label: label.trim(), value: value.trim() };
        });
        fieldDiv.dataset.options = JSON.stringify(options);
    }
});

templateForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const templateName = document.getElementById('templateName').value;
    const fields = Array.from(fieldsContainer.children).map(field => {
        const fieldData = {
            name: field.querySelector('input').value,
            type: field.querySelector('select').value
        };
        
        if (fieldData.type === 'select') {
            const options = JSON.parse(field.dataset.options || '[]');
            fieldData.options = options;
        }
        
        return fieldData;
    });

    const template = {
        name: templateName,
        fields: fields,
        createdAt: new Date().toISOString()
    };

    try {
        await db.saveTemplate(template);
        alert('模板保存成功！');
        showSection(templateManagement);
        loadTemplates();
    } catch (error) {
        alert('保存模板时出错：' + error);
    }
});

// Template Management
async function loadTemplates() {
    try {
        const templates = await db.getTemplates();
        const templatesList = document.getElementById('templatesList');
        templatesList.innerHTML = '';

        templates.forEach(template => {
            const card = document.createElement('div');
            card.className = 'template-card';
            
            card.innerHTML = `
                <div class="template-header">
                    <h3>${template.name}</h3>
                    <div class="template-actions">
                        <button onclick="editTemplate(${template.id})">编辑</button>
                        <button onclick="deleteTemplate(${template.id})">删除</button>
                    </div>
                </div>
                <div class="template-fields">
                    ${template.fields.map(field => `
                        <div class="field-display">
                            <div class="field-header">
                                <span class="field-name">${field.name}</span>
                                <span class="field-type">${fieldTypes.find(t => t.value === field.type)?.label || field.type}</span>
                            </div>
                            ${field.type === 'select' ? `
                                <div class="field-options">
                                    <div class="field-options-title">选项列表：</div>
                                    <div class="field-options-list">
                                        ${field.options.map(option => `
                                            <span class="field-option-item">${option.label}:${option.value}</span>
                                        `).join('')}
                                    </div>
                                </div>
                            ` : ''}
                        </div>
                    `).join('')}
                </div>
                <div class="template-footer">
                    <p>创建时间：${new Date(template.createdAt).toLocaleDateString()}</p>
                </div>
            `;
            
            templatesList.appendChild(card);
        });
    } catch (error) {
        alert('加载模板时出错：' + error);
    }
}

async function editTemplate(id) {
    try {
        const template = await db.getTemplate(id);
        showSection(templateCreation);
        
        // 填充模板名称
        document.getElementById('templateName').value = template.name;
        
        // 清空并重新创建字段
        fieldsContainer.innerHTML = '';
        
        template.fields.forEach(field => {
            const fieldDiv = document.createElement('div');
            fieldDiv.className = 'field-item';
            
            const fieldName = document.createElement('input');
            fieldName.type = 'text';
            fieldName.placeholder = '字段名称';
            fieldName.value = field.name;
            fieldName.required = true;

            const fieldType = document.createElement('select');
            fieldType.required = true;
            fieldTypes.forEach(type => {
                const option = document.createElement('option');
                option.value = type.value;
                option.textContent = type.label;
                option.selected = type.value === field.type;
                fieldType.appendChild(option);
            });

            const optionsContainer = document.createElement('div');
            optionsContainer.className = `options-container ${field.type === 'select' ? '' : 'hidden'}`;
            optionsContainer.innerHTML = `
                <div class="options-input-container">
                    <textarea class="options-textarea" placeholder="请输入选项，格式：选项1:值1&#10;选项2:值2"></textarea>
                    <button type="button" class="add-option-btn">添加选项</button>
                </div>
                <div class="options-list"></div>
                <div class="options-format">
                    <small>格式说明：每行一个选项，格式为"选项:值"，例如：</small>
                    <pre>选项1:值1
选项2:值2
选项3:值3</pre>
                </div>
            `;

            // 如果是下拉框类型，显示现有选项
            if (field.type === 'select' && field.options) {
                const optionsList = optionsContainer.querySelector('.options-list');
                field.options.forEach(option => {
                    const optionDiv = document.createElement('div');
                    optionDiv.className = 'option-item';
                    optionDiv.innerHTML = `
                        <span>${option.label}:${option.value}</span>
                        <button type="button" class="remove-option-btn">×</button>
                    `;
                    
                    optionDiv.querySelector('.remove-option-btn').onclick = () => {
                        optionDiv.remove();
                        updateOptionsData(fieldDiv);
                    };
                    
                    optionsList.appendChild(optionDiv);
                });
                // 保存现有选项数据
                fieldDiv.dataset.options = JSON.stringify(field.options);
            }

            const removeBtn = document.createElement('button');
            removeBtn.textContent = '删除';
            removeBtn.type = 'button';
            removeBtn.onclick = () => fieldDiv.remove();

            fieldDiv.appendChild(fieldName);
            fieldDiv.appendChild(fieldType);
            fieldDiv.appendChild(optionsContainer);
            fieldDiv.appendChild(removeBtn);
            fieldsContainer.appendChild(fieldDiv);

            // 监听字段类型变化
            fieldType.addEventListener('change', () => {
                optionsContainer.classList.toggle('hidden', fieldType.value !== 'select');
                if (fieldType.value !== 'select') {
                    delete fieldDiv.dataset.options;
                }
            });

            // 添加选项按钮事件
            const addOptionBtn = optionsContainer.querySelector('.add-option-btn');
            addOptionBtn.addEventListener('click', () => {
                const textarea = optionsContainer.querySelector('.options-textarea');
                const optionsList = optionsContainer.querySelector('.options-list');
                const options = textarea.value.split('\n')
                    .map(line => line.trim())
                    .filter(line => line)
                    .map(line => {
                        const [label, value] = line.split(':').map(s => s.trim());
                        return { label, value: value || label };
                    });
                
                if (options.length > 0) {
                    optionsList.innerHTML = '';
                    options.forEach(option => {
                        const optionDiv = document.createElement('div');
                        optionDiv.className = 'option-item';
                        optionDiv.innerHTML = `
                            <span>${option.label}:${option.value}</span>
                            <button type="button" class="remove-option-btn">×</button>
                        `;
                        
                        optionDiv.querySelector('.remove-option-btn').onclick = () => {
                            optionDiv.remove();
                            updateOptionsData(fieldDiv);
                        };
                        
                        optionsList.appendChild(optionDiv);
                    });
                    textarea.value = '';
                    updateOptionsData(fieldDiv);
                }
            });
        });

        // 修改表单提交处理
        const originalSubmitHandler = templateForm.onsubmit;
        templateForm.onsubmit = async (e) => {
            e.preventDefault();
            
            const templateName = document.getElementById('templateName').value;
            const fields = Array.from(fieldsContainer.children).map(field => {
                const fieldData = {
                    name: field.querySelector('input').value,
                    type: field.querySelector('select').value
                };
                
                if (fieldData.type === 'select') {
                    const options = JSON.parse(field.dataset.options || '[]');
                    fieldData.options = options;
                }
                
                return fieldData;
            });

            const updatedTemplate = {
                id: id,
                name: templateName,
                fields: fields,
                createdAt: template.createdAt
            };

            try {
                await db.updateTemplate(updatedTemplate);
                alert('模板更新成功！');
                showSection(templateManagement);
                loadTemplates();
                // 恢复原始提交处理
                templateForm.onsubmit = originalSubmitHandler;
            } catch (error) {
                alert('更新模板时出错：' + error);
            }
        };
    } catch (error) {
        alert('加载模板时出错：' + error);
    }
}

async function deleteTemplate(id) {
    if (confirm('确定要删除这个模板吗？')) {
        try {
            await db.deleteTemplate(id);
            loadTemplates();
        } catch (error) {
            alert('删除模板时出错：' + error);
        }
    }
}

// Data Entry
async function loadTemplateSelect() {
    try {
        const templates = await db.getTemplates();
        templateSelect.innerHTML = '<option value="">请选择模板</option>';
        
        templates.forEach(template => {
            const option = document.createElement('option');
            option.value = template.id;
            option.textContent = template.name;
            templateSelect.appendChild(option);
        });
    } catch (error) {
        alert('加载模板时出错：' + error);
    }
}

templateSelect.addEventListener('change', async () => {
    const templateId = templateSelect.value;
    if (!templateId) return;

    try {
        const template = await db.getTemplate(parseInt(templateId));
        dataEntryForm.innerHTML = '';

        template.fields.forEach(field => {
            const formGroup = document.createElement('div');
            formGroup.className = 'form-group';

            const label = document.createElement('label');
            label.textContent = field.name;

            let input;
            switch (field.type) {
                case 'textarea':
                    input = document.createElement('textarea');
                    break;
                case 'select':
                    input = document.createElement('select');
                    field.options.forEach(option => {
                        const opt = document.createElement('option');
                        opt.value = option.value;
                        opt.textContent = option.label;
                        input.appendChild(opt);
                    });
                    break;
                case 'image':
                    const imageContainer = document.createElement('div');
                    imageContainer.className = 'image-upload-container';
                    imageContainer.innerHTML = `
                        <input type="file" accept="image/*" style="display: none">
                        <p>点击或拖拽图片到此处上传</p>
                        <img class="image-preview" style="display: none">
                    `;
                    const fileInput = imageContainer.querySelector('input');
                    const preview = imageContainer.querySelector('.image-preview');
                    
                    imageContainer.addEventListener('click', () => fileInput.click());
                    imageContainer.addEventListener('dragover', (e) => {
                        e.preventDefault();
                        imageContainer.style.borderColor = '#3498db';
                    });
                    imageContainer.addEventListener('dragleave', () => {
                        imageContainer.style.borderColor = '#ddd';
                    });
                    imageContainer.addEventListener('drop', (e) => {
                        e.preventDefault();
                        imageContainer.style.borderColor = '#ddd';
                        const file = e.dataTransfer.files[0];
                        if (file && file.type.startsWith('image/')) {
                            handleImageUpload(file, preview);
                        }
                    });
                    
                    fileInput.addEventListener('change', (e) => {
                        const file = e.target.files[0];
                        if (file) {
                            handleImageUpload(file, preview);
                        }
                    });
                    
                    formGroup.appendChild(label);
                    formGroup.appendChild(imageContainer);
                    dataEntryForm.appendChild(formGroup);
                    return;
                default:
                    input = document.createElement('input');
                    input.type = field.type;
            }

            if (input) {
                input.required = true;
                input.name = field.name;
                formGroup.appendChild(label);
                formGroup.appendChild(input);
                dataEntryForm.appendChild(formGroup);
            }
        });
    } catch (error) {
        alert('加载模板时出错：' + error);
    }
});

async function handleImageUpload(file, preview) {
    try {
        // 这里使用 imgbb 的 API 作为示例
        const formData = new FormData();
        formData.append('image', file);
        
        const response = await fetch('https://api.imgbb.com/1/upload?key=YOUR_IMGBB_API_KEY', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        if (data.success) {
            preview.src = data.data.url;
            preview.style.display = 'block';
            preview.dataset.url = data.data.url;
        } else {
            throw new Error('图片上传失败');
        }
    } catch (error) {
        alert('图片上传失败：' + error);
    }
}

saveDataBtn.addEventListener('click', async () => {
    const templateId = templateSelect.value;
    if (!templateId) {
        alert('请先选择模板');
        return;
    }

    try {
        const template = await db.getTemplate(parseInt(templateId));
        const data = {
            templateId: parseInt(templateId),
            values: {},
            createdAt: new Date().toISOString()
        };

        // 处理表单数据
        const formGroups = dataEntryForm.querySelectorAll('.form-group');
        formGroups.forEach(group => {
            const label = group.querySelector('label');
            const fieldName = label.textContent;
            const input = group.querySelector('input, select, textarea');
            
            if (input) {
                if (input.type === 'file') {
                    // 跳过文件输入框
                    return;
                }
                
                // 对于下拉框，保存选项的标签而不是值
                if (input.tagName === 'SELECT') {
                    const field = template.fields.find(f => f.name === fieldName);
                    if (field && field.type === 'select') {
                        const option = field.options.find(opt => opt.value === input.value);
                        data.values[fieldName] = option ? option.label : input.value;
                    } else {
                        data.values[fieldName] = input.value;
                    }
                } else {
                    data.values[fieldName] = input.value;
                }
            }
        });

        // 处理图片数据
        const imagePreviews = dataEntryForm.querySelectorAll('.image-preview');
        imagePreviews.forEach(preview => {
            if (preview.dataset.url) {
                const fieldName = preview.closest('.form-group').querySelector('label').textContent;
                data.values[fieldName] = preview.dataset.url;
            }
        });

        // 保存数据到 IndexedDB
        await db.saveData(data);
        
        // 清空表单
        formGroups.forEach(group => {
            const input = group.querySelector('input, select, textarea');
            if (input) {
                if (input.type === 'file') {
                    // 跳过文件输入框
                    return;
                }
                input.value = '';
            }
        });
        
        // 清空图片预览
        imagePreviews.forEach(preview => {
            preview.src = '';
            preview.style.display = 'none';
            delete preview.dataset.url;
        });

        alert('数据保存成功！');
        
        // 可选：自动刷新数据视图
        if (viewTemplateSelect.value === templateId) {
            viewTemplateSelect.dispatchEvent(new Event('change'));
        }
    } catch (error) {
        console.error('保存数据时出错：', error);
        alert('保存数据时出错：' + error.message);
    }
});

// Data View
async function loadViewTemplateSelect() {
    try {
        const templates = await db.getTemplates();
        viewTemplateSelect.innerHTML = '<option value="">请选择模板</option>';
        
        templates.forEach(template => {
            const option = document.createElement('option');
            option.value = template.id;
            option.textContent = template.name;
            viewTemplateSelect.appendChild(option);
        });
    } catch (error) {
        alert('加载模板时出错：' + error);
    }
}

viewTemplateSelect.addEventListener('change', async () => {
    const templateId = viewTemplateSelect.value;
    if (!templateId) return;

    try {
        const template = await db.getTemplate(parseInt(templateId));
        const data = await db.getDataByTemplate(parseInt(templateId));
        
        // 创建表格
        const table = document.createElement('table');
        table.className = 'data-table';
        
        // 创建表头
        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');
        template.fields.forEach(field => {
            const th = document.createElement('th');
            th.textContent = field.name;
            headerRow.appendChild(th);
        });
        thead.appendChild(headerRow);
        table.appendChild(thead);
        
        // 创建表体
        const tbody = document.createElement('tbody');
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const pageData = data.slice(startIndex, endIndex);
        
        pageData.forEach(item => {
            const row = document.createElement('tr');
            template.fields.forEach(field => {
                const td = document.createElement('td');
                const value = item.values[field.name];
                
                if (field.type === 'image' && value) {
                    const img = document.createElement('img');
                    img.src = value;
                    img.style.maxWidth = '100px';
                    img.style.maxHeight = '100px';
                    td.appendChild(img);
                } else {
                    td.textContent = value || '';
                }
                
                row.appendChild(td);
            });
            tbody.appendChild(row);
        });
        
        table.appendChild(tbody);
        
        // 更新分页信息
        const totalPages = Math.ceil(data.length / itemsPerPage);
        pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
        
        // 更新数据视图
        dataViewContainer.innerHTML = '';
        dataViewContainer.appendChild(table);
    } catch (error) {
        alert('加载数据时出错：' + error);
    }
});

// 分页控制
prevPageBtn.addEventListener('click', () => {
    if (currentPage > 1) {
        currentPage--;
        const templateId = viewTemplateSelect.value;
        if (templateId) {
            viewTemplateSelect.dispatchEvent(new Event('change'));
        }
    }
});

nextPageBtn.addEventListener('click', () => {
    currentPage++;
    const templateId = viewTemplateSelect.value;
    if (templateId) {
        viewTemplateSelect.dispatchEvent(new Event('change'));
    }
});

// Batch Download
async function loadDownloadTemplateSelect() {
    try {
        const templates = await db.getTemplates();
        downloadTemplateSelect.innerHTML = '<option value="">请选择模板</option>';
        
        templates.forEach(template => {
            const option = document.createElement('option');
            option.value = template.id;
            option.textContent = template.name;
            downloadTemplateSelect.appendChild(option);
        });
    } catch (error) {
        alert('加载模板时出错：' + error);
    }
}

downloadBtn.addEventListener('click', async () => {
    const templateId = downloadTemplateSelect.value;
    const format = document.getElementById('downloadFormat').value;
    
    if (!templateId) {
        alert('请先选择模板');
        return;
    }

    try {
        const template = await db.getTemplate(parseInt(templateId));
        const data = await db.getDataByTemplate(parseInt(templateId));
        
        let content;
        let filename;
        let type;

        switch (format) {
            case 'csv':
                content = convertToCSV(template, data);
                filename = `${template.name}_数据.csv`;
                type = 'text/csv';
                break;
            case 'json':
                content = JSON.stringify(data, null, 2);
                filename = `${template.name}_数据.json`;
                type = 'application/json';
                break;
            case 'excel':
                content = convertToExcel(template, data);
                filename = `${template.name}_数据.xlsx`;
                type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                break;
            case 'word':
                content = await convertToWord(template, data);
                filename = `${template.name}_数据.docx`;
                type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                break;
        }

        downloadFile(content, filename, type);
    } catch (error) {
        alert('准备下载时出错：' + error);
    }
});

// Utility Functions
function convertToCSV(template, data) {
    const headers = template.fields.map(field => field.name);
    const rows = data.map(item => 
        headers.map(header => item.values[header])
    );
    
    return [
        headers.join(','),
        ...rows.map(row => row.join(','))
    ].join('\n');
}

function convertToExcel(template, data) {
    // 这是一个简化版本。在实际应用中，
    // 你会使用像 SheetJS 这样的库来创建正确的 Excel 文件
    return convertToCSV(template, data);
}

function downloadFile(content, filename, type) {
    const blob = new Blob([content], { type });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 添加 Word 文档转换函数
async function convertToWord(template, data) {
    // 创建 Word 文档内容
    let docContent = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>`;

    // 添加标题
    docContent += `
        <w:p>
            <w:r>
                <w:t>${template.name}</w:t>
            </w:r>
        </w:p>`;

    // 为每条数据创建一个表格
    data.forEach((item, index) => {
        docContent += `
        <w:p>
            <w:r>
                <w:t>记录 ${index + 1}</w:t>
            </w:r>
        </w:p>
        <w:tbl>
            <w:tr>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>字段</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>值</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
            </w:tr>`;

        template.fields.forEach(field => {
            const value = item.values[field.name] || '';
            docContent += `
            <w:tr>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>${field.name}</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>${value}</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
            </w:tr>`;
        });

        docContent += `
        </w:tbl>`;
    });

    docContent += `
    </w:body>
</w:document>`;

    // 创建 ZIP 文件（Word 文档实际上是一个 ZIP 文件）
    const zip = new JSZip();
    zip.file("word/document.xml", docContent);
    
    // 添加必要的 Word 文档结构文件
    zip.file("[Content_Types].xml", `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
    <Default Extension="xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
</Types>`);

    // 生成 ZIP 文件
    return await zip.generateAsync({type: "blob"});
}

// 更新仪表盘数据
async function updateDashboard() {
    try {
        const templates = await db.getTemplates();
        const allData = await db.getAllData();
        
        // 更新基础统计数据
        document.getElementById('templateCount').textContent = templates.length;
        document.getElementById('totalDataCount').textContent = allData.length;
        
        // 计算今日新增数据
        const today = new Date().toISOString().split('T')[0];
        const todayData = allData.filter(item => 
            item.createdAt.startsWith(today)
        );
        document.getElementById('todayDataCount').textContent = todayData.length;
        
        // 字段类型分布图表
        const fieldTypeChart = echarts.init(document.getElementById('fieldTypeChart'));
        const fieldTypeData = {};
        templates.forEach(template => {
            template.fields.forEach(field => {
                fieldTypeData[field.type] = (fieldTypeData[field.type] || 0) + 1;
            });
        });
        
        fieldTypeChart.setOption({
            title: {
                text: '字段类型分布',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                type: 'pie',
                radius: '50%',
                data: Object.entries(fieldTypeData).map(([type, count]) => ({
                    name: fieldTypes.find(t => t.value === type)?.label || type,
                    value: count
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }]
        });
        
        // 数据录入趋势图表
        const dataTrendChart = echarts.init(document.getElementById('dataTrendChart'));
        const trendData = {};
        allData.forEach(item => {
            const date = item.createdAt.split('T')[0];
            trendData[date] = (trendData[date] || 0) + 1;
        });
        
        dataTrendChart.setOption({
            title: {
                text: '数据录入趋势',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: Object.keys(trendData).sort()
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                data: Object.keys(trendData).sort().map(date => trendData[date]),
                type: 'line',
                smooth: true,
                areaStyle: {
                    opacity: 0.3
                }
            }]
        });
        
        // 模板使用情况图表
        const templateUsageChart = echarts.init(document.getElementById('templateUsageChart'));
        const usageData = {};
        allData.forEach(item => {
            const template = templates.find(t => t.id === item.templateId);
            if (template) {
                usageData[template.name] = (usageData[template.name] || 0) + 1;
            }
        });
        
        templateUsageChart.setOption({
            title: {
                text: '模板使用情况',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'value'
            },
            yAxis: {
                type: 'category',
                data: Object.keys(usageData)
            },
            series: [{
                data: Object.values(usageData),
                type: 'bar',
                showBackground: true,
                backgroundStyle: {
                    color: 'rgba(180, 180, 180, 0.2)'
                }
            }]
        });
        
        // 监听窗口大小变化，调整图表大小
        window.addEventListener('resize', () => {
            fieldTypeChart.resize();
            dataTrendChart.resize();
            templateUsageChart.resize();
        });
        
    } catch (error) {
        console.error('更新仪表盘时出错：', error);
        alert('更新仪表盘时出错：' + error.message);
    }
}

// 添加文件导入导出相关元素
const importFileInput = document.createElement('input');
importFileInput.type = 'file';
importFileInput.accept = '.json';
importFileInput.style.display = 'none';
document.body.appendChild(importFileInput);

// 数据导入导出功能
async function exportDataToFile() {
    try {
        const templates = await db.getTemplates();
        const allData = await db.getAllData();
        
        const exportData = {
            templates,
            data: allData,
            exportDate: new Date().toISOString()
        };
        
        const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `webBatchCreate_backup_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    } catch (error) {
        console.error('导出数据时出错：', error);
    }
}

async function importDataFromFile(file) {
    try {
        const text = await file.text();
        const importData = JSON.parse(text);
        
        // 验证导入数据的格式
        if (!importData.templates || !importData.data) {
            throw new Error('无效的数据格式');
        }
        
        // 清空现有数据
        await db.clearAllData();
        
        // 导入模板
        for (const template of importData.templates) {
            await db.saveTemplate(template);
        }
        
        // 导入数据
        for (const data of importData.data) {
            await db.saveData(data);
        }
        
        alert('数据导入成功！');
        
        // 刷新当前视图
        if (dashboard.classList.contains('hidden')) {
            const currentSection = document.querySelector('section:not(.hidden)');
            if (currentSection) {
                showSection(currentSection);
            }
        } else {
            updateDashboard();
        }
    } catch (error) {
        console.error('导入数据时出错：', error);
        alert('导入数据时出错：' + error.message);
    }
}

// 监听文件导入
importFileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) {
        importDataFromFile(file);
        e.target.value = ''; // 清空文件选择
    }
});

// 监听浏览器关闭事件
window.addEventListener('beforeunload', (e) => {
    // exportDataToFile();
});

// 添加导入按钮到侧边栏
const importBtn = document.createElement('button');
importBtn.textContent = '导入数据';
importBtn.className = 'sidebar-btn';
importBtn.onclick = () => importFileInput.click();
// document.querySelector('.sidebar').appendChild(importBtn); 